package com.wyl.studyredis.business.controller;


import cn.hutool.core.util.StrUtil;
import com.wyl.studyredis.business.dto.CarAddDto;
import com.wyl.studyredis.business.dto.CarUpdateDto;
import com.wyl.studyredis.business.entity.Car;
import com.wyl.studyredis.business.service.ICarService;
import com.wyl.studyredis.business.vo.CarVo;
import com.wyl.studyredis.framework.ResponseVo;
import com.wyl.studyredis.framework.util._BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wyl
 * @since 2022-02-13
 */
@RestController
@RequestMapping("/car")
public class CarController {

    @Autowired
    private ICarService carService;

    @GetMapping("/getById")
    public ResponseVo<CarVo> get(@RequestParam("id") String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseVo.fail("主键不能为空");
        }
        try {
            CarVo vo = carService.getByIdAndCache(id);
            return ResponseVo.success(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseVo.error(e.getMessage());
        }
    }

    @PostMapping("/add")
    public ResponseVo<String> add(@RequestBody @Valid CarAddDto dto) {
        try {
            Car car = _BeanUtil.copyProperties(dto, Car.class);
            carService.saveAndCache(car);
            return ResponseVo.success(car.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseVo.error(e.getMessage());
        }
    }

    @PostMapping("/update")
    public ResponseVo<String> update(@RequestBody @Valid CarUpdateDto dto) {
        try {
            Car car = _BeanUtil.copyProperties(dto, Car.class);
            carService.updateByIdAndCache(car);
            return ResponseVo.success(car.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseVo.error(e.getMessage());
        }
    }

    @GetMapping("/delete")
    public ResponseVo delete(@RequestParam("id") String id){
        if (StrUtil.isBlank(id)) {
            return ResponseVo.fail("主键不能为空");
        }
        carService.removeByIdAndCache(id);
        return ResponseVo.success();
    }

}

